package com.ruoyi.jiajia.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 社工提现Controller
 *
 * @author knd
 * @date 2021-11-02
 */
@Controller
@RequestMapping("/jiajia/workerTiXian")
public class JiajiaWorkerTixianController extends BaseController
{
    private String prefix = "jiajia/workerTiXian";

    @Autowired
    private IJiajiaWorkerTixianService jiajiaWorkerTixianService;

    @Autowired
    private IJiajiaWorkerService workerService;

    @Autowired
    private IJiajiaMessageService messageService;

    @Autowired
    private IJiajiaWorkerMoneyChangeService workerMoneyChangeService;

    @Autowired
    private IJiajiaWorkerBankCardService bankCardService;

    @RequiresPermissions("jiajia:workerTiXian:view")
    @GetMapping()
    public String workerTiXian()
    {
        return prefix + "/workerTiXian";
    }

    /**
     * 查询社工提现列表
     */
    @RequiresPermissions("jiajia:workerTiXian:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(JiajiaWorkerTixian jiajiaWorkerTixian)
    {
        startPage();
        List<JiajiaWorkerTixian> list = jiajiaWorkerTixianService.selectJiajiaWorkerTixianList(jiajiaWorkerTixian);

        JiajiaWorkerBankCard bankCard = new JiajiaWorkerBankCard();
        bankCard.getParams().put("widsArr",StringUtils.listsToSbStr(list,"wid"));
        List<JiajiaWorkerBankCard> bankCardList = bankCardService.selectJiajiaWorkerBankCardList(bankCard);

        Map<String,List<JiajiaWorkerBankCard>> bankMap = new HashMap<>();
        for (JiajiaWorkerBankCard model : bankCardList) {
            if (!bankMap.containsKey(model.getWid().toString())){
                bankMap.put(model.getWid().toString(),new ArrayList<>());
            }
            bankMap.get(model.getWid().toString()).add(model);
        }

        for (JiajiaWorkerTixian model : list) {
            model.getParams().put("bankList",new ArrayList<>());
            if (bankMap.containsKey(model.getWid().toString())){
                model.getParams().put("bankList",bankMap.get(model.getWid().toString()));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出社工提现列表
     */
    @RequiresPermissions("jiajia:workerTiXian:export")
    @Log(title = "社工提现", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(JiajiaWorkerTixian jiajiaWorkerTixian)
    {
        List<JiajiaWorkerTixian> list = jiajiaWorkerTixianService.selectJiajiaWorkerTixianList(jiajiaWorkerTixian);
        ExcelUtil<JiajiaWorkerTixian> util = new ExcelUtil<JiajiaWorkerTixian>(JiajiaWorkerTixian.class);
        return util.exportExcel(list, "社工提现数据");
    }

    /**
     * 新增社工提现
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存社工提现
     */
    @RequiresPermissions("jiajia:workerTiXian:add")
    @Log(title = "社工提现", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(JiajiaWorkerTixian jiajiaWorkerTixian)
    {
        return toAjax(jiajiaWorkerTixianService.insertJiajiaWorkerTixian(jiajiaWorkerTixian));
    }

    /**
     * 修改社工提现
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        JiajiaWorkerTixian jiajiaWorkerTixian = jiajiaWorkerTixianService.selectJiajiaWorkerTixianById(id);
        mmap.put("jiajiaWorkerTixian", jiajiaWorkerTixian);
        return prefix + "/edit";
    }

    /**
     * 修改保存社工提现
     */
    @RequiresPermissions("jiajia:workerTiXian:edit")
    @Log(title = "社工提现", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(JiajiaWorkerTixian jiajiaWorkerTixian)
    {
        return toAjax(jiajiaWorkerTixianService.updateJiajiaWorkerTixian(jiajiaWorkerTixian));
    }

    /**
     * 删除社工提现
     */
    @RequiresPermissions("jiajia:workerTiXian:remove")
    @Log(title = "社工提现", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(jiajiaWorkerTixianService.deleteJiajiaWorkerTixianByIds(ids));
    }

    /**
     * 审核提现
     */
    @RequiresPermissions("jiajia:workerTiXian:review")
    @PostMapping("/shenHeTiXian")
    @ResponseBody
    @Transactional
    public AjaxResult shenHeTiXian(JiajiaWorkerTixian jiajiaWorkerTixian)
    {
        JiajiaWorkerTixian tixian = jiajiaWorkerTixianService.selectJiajiaWorkerTixianById(jiajiaWorkerTixian.getId());
        if (tixian == null)return AjaxResult.refreshAgain();

        JiajiaWorker worker = workerService.selectJiajiaWorkerById(tixian.getWid());
        if (worker == null)return AjaxResult.refreshAgain();


        //1。如果审核通过（创建message，社工余额变动记录，修改社工余额）
        if (jiajiaWorkerTixian.getStatus().intValue()==1){
            JiajiaMessage message = new JiajiaMessage();
            message.setType(1);
            message.setUid(tixian.getWid());
            message.setTitle("提现成功");
            message.setContent("您的余额已提现，共计:"+tixian.getMoney().setScale(2, RoundingMode.HALF_UP)+"元");
            messageService.insertJiajiaMessage(message);

            //新增社工余额变动记录
            JiajiaWorkerMoneyChange workerMoneyChange=new JiajiaWorkerMoneyChange();
            workerMoneyChange.setWid(tixian.getWid());
            workerMoneyChange.setChangemoney(new BigDecimal( - tixian.getMoney().floatValue()));
            workerMoneyChange.setChangeAfter(new BigDecimal(worker.getMoney().floatValue() - tixian.getMoney().floatValue()));
            workerMoneyChange.setChangeBefor(worker.getMoney());
            workerMoneyChange.setType("提现成功");
            workerMoneyChange.setDes("提现金额："+tixian.getMoney().setScale(2,RoundingMode.HALF_UP));
            workerMoneyChangeService.insertJiajiaWorkerMoneyChange(workerMoneyChange);

        }else {

            if (StringUtils.isEmpty(jiajiaWorkerTixian.getCause())){
                return AjaxResult.error("请输入驳回原因");
            }

            //如果驳回（创建message，余额返回）
            JiajiaMessage message = new JiajiaMessage();
            message.setType(1);
            message.setUid(tixian.getWid());
            message.setTitle("提现失败");
            message.setContent("您申请的提现("+tixian.getMoney().setScale(2,RoundingMode.HALF_UP)+"元)被驳回,驳回原因:"
                    +jiajiaWorkerTixian.getCause());
            messageService.insertJiajiaMessage(message);

            //新增社工余额变动记录
            JiajiaWorkerMoneyChange workerMoneyChange=new JiajiaWorkerMoneyChange();
            workerMoneyChange.setWid(tixian.getWid());
            workerMoneyChange.setChangemoney(new BigDecimal( tixian.getMoney().floatValue()));
            workerMoneyChange.setChangeAfter(new BigDecimal(worker.getMoney().floatValue() + tixian.getMoney().floatValue()));
            workerMoneyChange.setChangeBefor(worker.getMoney());
            workerMoneyChange.setType("提现失败");
            workerMoneyChange.setDes("提现金额："+tixian.getMoney().setScale(2,RoundingMode.HALF_UP)+"元,被驳回,返还至余额");
            workerMoneyChangeService.insertJiajiaWorkerMoneyChange(workerMoneyChange);

            //社工余额修改
            worker.setMoney(workerMoneyChange.getChangeAfter());
            workerService.updateJiajiaWorker(worker);

        }
        jiajiaWorkerTixian.setStime(new Date());
        return toAjax(jiajiaWorkerTixianService.updateJiajiaWorkerTixian(jiajiaWorkerTixian));
    }


}
